package com.ztomorrow.ying_cun_plus.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.ztomorrow.ying_cun_plus.dao.mapper.BookInfoMapper;
import com.ztomorrow.ying_cun_plus.dao.po.BookInfo;
import com.ztomorrow.ying_cun_plus.dto.EsBookDto;
import com.ztomorrow.ying_cun_plus.dto.resp.BookInfoRespDto;
import com.ztomorrow.ying_cun_plus.service.BookService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.awt.print.Book;
import java.io.IOException;
import java.time.ZoneOffset;

import static com.ztomorrow.ying_cun_plus.constant.author.SystemConstant.*;

@Component
@RequiredArgsConstructor
@Slf4j
public class EsListener {

    private final RestHighLevelClient client;
    private final BookInfoMapper bookInfoMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = ES_UPDATE_QUEUE,
                    arguments = @Argument(name = "x-queue-mode", value = "lazy")),
            exchange = @Exchange(name = BOOK_ID_DIRECT),
            key = UPDATE_ROUTING_KEY
    ))
    public void listen(Long bookId) throws IOException {
        BookInfo bookInfo = bookInfoMapper.selectById(bookId);
        EsBookDto esBookDto = BeanUtil.copyProperties(bookInfo, EsBookDto.class);
        esBookDto.setLastChapterUpdateTime(bookInfo.getLastChapterUpdateTime()
                .toInstant(ZoneOffset.ofHours(8)).toEpochMilli());

        IndexRequest request = new IndexRequest(INDEX_BOOK).id(bookId.toString());
        request.source(JSONUtil.toJsonStr(esBookDto), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }
}

